package com.cyh.structurealgorithm;

public class BinarySearchNoRecur {
    public static void test() {
        int arr[] = {-8, -2, -2, -1, 3, 3, 5, 9, 10, 10, 11};
        int resIndex = binarySearch(arr, 9);
        int resIndex2 = binarySearch(arr,  100);
        System.out.println("查找的下标：resIndex = " + resIndex + " resIndex2 = " + resIndex2);
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(arr[mid] == target) {
                return mid;
            } else if(arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
